import vueI18n from '@intlify/unplugin-vue-i18n/vite'
import terser from '@rollup/plugin-terser'
import unHeadVite from '@unhead/addons/vite'
import basicSsl from '@vitejs/plugin-basic-ssl'
import legacyPlugin from '@vitejs/plugin-legacy'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import { defineConfig } from 'vite'
import eslintPlugin from 'vite-plugin-eslint'
import { viteMockServe } from 'vite-plugin-mock'
import svgLoader from 'vite-svg-loader'

const getOutputDir = () => {
  const args = process.argv.slice(2)
  if (args.includes('staging')) {
    return 'dist-staging'
  }
  return 'dist'
}

const plugins = [
  vue(),
  legacyPlugin(),
  eslintPlugin({ cache: false }),
  vueI18n({
    include: resolve(__dirname, 'src/i18n/locale/**'),
  }),
  viteMockServe({
    mockPath: 'src/mock',
    localEnabled: true,
    prodEnabled: false,
    watchFiles: true,
    logger: true,
  }),
  svgLoader(),
]

if (process.env.SSL === 'true') {
  plugins.push(
    basicSsl({
      /** name of certification */
      name: 'fantasi-dev',
      /** custom trust domains */
      domains: ['*.fantasi-dev.com'],
      /** directory of certification, if not exists, consider generate it by ./docs/ssl.md */
      certDir: './docker/nginx/ssl',
    }),
  )
}

function getChunkName(id, folderName) {
  const path = id.toString().split(`${folderName}/`)[1].split('/')
  if (path.length > 1) {
    return path.join('-').split('.')[0].toString()
  } else {
    let r = path[0].split('.')[0].toString()
    if (r === 'index') r = `${folderName}-${r}`
    return r
  }
}

/**
 * @description 打包時的chunk分類，依照src底下的資料夾名稱分類
 */
const folders = [
  'store',
  'compositions',
  'constant',
  'schema',
  'worker',
  'ws',
  'errors',
  'gtm',
  'http',
  'router',
  'plugins',
]

// https://vitejs.dev/config/
export default defineConfig({
  build: {
    minify: 'terser',
    rollupOptions: {
      plugins: [terser(), unHeadVite()],
      input: {
        main: resolve(__dirname, 'index.html'),
      },
      output: {
        manualChunks: (id) => {
          for (const folder of folders) {
            if (id.includes(`/${folder}/`)) return getChunkName(id, folder)
          }
          if (id.includes('node_modules')) {
            return id.toString().split('node_modules/')[1].split('/')[0].toString()
          }
        },
      },
    },
    terserOptions: {
      compress: {
        drop_console: process.env.APP_ENV === 'production',
      },
    },
    outDir: getOutputDir(),
  },
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src'),
      '@comp': resolve(__dirname, 'src/components'),
      '@use': resolve(__dirname, 'src/compositions'),
      '@const': resolve(__dirname, 'src/constant'),
    },
  },
  plugins,
  server: {
    host: '0.0.0.0',
    proxy: {
      '/api': {
        target: 'https://fantasi-api.yesebo.net',
        changeOrigin: true,
      },
    },
    https: process.env.SSL === 'true',
  },
})
